import { login } from '@/services/api_user';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormCheckbox, ProFormText } from '@ant-design/pro-components';
import { history, useModel, Helmet } from '@umijs/max';
import { Alert, message } from 'antd';
import React, { useState } from 'react';
// 函数用于强制 React 立即执行所有的更新队列，并同步刷新 DOM。通常情况下，React 会批量处理状态更新和其他副作用，以优化性能。这意味着即使你连续调用多个状态更新函数，React 也可能会将它们合并成一次更新来减少重新渲染的次数。
import { flushSync } from 'react-dom';
// 是 Ant Design 团队提供的一个用于创建样式钩子的库，它允许开发者使用类似于 styled - components 或 @emotion/styled 的方式来定义组件样式。通过 antd-style 中的 createStyles，你可以更方便地为 Ant Design 组件或自定义 React 组件添加内联样式，同时保持样式逻辑与组件逻辑紧密耦合。
import { createStyles } from 'antd-style';
import Footer from '@/components/Footer';
import { LoginParams, LoginResult } from '@/services/types';
import Settings from '../../../config/defaultSettings';

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundSize: '100% 100%',
    },
  };
});

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<LoginResult>();
  // https://umijs.org/docs/max/data-flow#全局初始状态
  const { initialState, setInitialState } = useModel('@@initialState');
  const { styles } = useStyles();


  const handleSubmit = async (values: LoginParams) => {
    // 登录: 取 code
    const res: LoginResult = await login({ ...values });
    if (res.success === true) {
      message.success('登录成功！');
      const userInfo = await initialState?.fetchUserInfo?.();
      // 保存用户信息
      if (userInfo) {
        flushSync(() => {
          setInitialState((s) => ({
            ...s,
            currentUser: userInfo,
          }));
        });
      }
      const urlParams = new URL(window.location.href).searchParams;
      history.push(urlParams.get('redirect') || '/');
      return;
    }
    message.error('登录失败，请重试！');
    // 如果失败去设置用户错误信息
    setUserLoginState(res);
  };

  return (
    <div className={styles.container}>
      <Helmet>
        <title>登录页</title>
      </Helmet>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          logo={<img alt="logo" src={Settings.logo} />}
          title={Settings.title}
          subTitle="专注期货 IT"
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            await handleSubmit(values as LoginParams);
          }}
        >
          {userLoginState?.success === false && (
            <LoginMessage content="账户或密码错误" />
          )}

          <>
            <ProFormText
              name="username"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined />,
              }}
              placeholder="用户名: admin or user"
              rules={[
                {
                  required: true,
                  message: '请输入用户名!',
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined />,
              }}
              placeholder="密码: ant.design"
              rules={[
                {
                  required: true,
                  message: '请输入密码！',
                },
              ]}
            />
          </>

          <div
            style={{
              marginBottom: 24,
            }}
          >
            <ProFormCheckbox noStyle name="autoLogin">
              自动登录
            </ProFormCheckbox>
            <a
              style={{
                float: 'right',
              }}
            >
              忘记密码
            </a>
          </div>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
